<template>
  <el-form inline :model="form">
    <el-form-item label="账套名称">
      <el-select
        v-model="form.projectSetBelongId"
        clearable
        placeholder="请选择账套名称"
        size="large"
      >
        <el-option
          v-for="(item, index) in projectSetBelong"
          :key="index"
          :label="item.projectSetBelongName"
          :value="item.projectSetBelongId"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="年度">
      <el-date-picker
        size="large"
        :clearable="false"
        v-model="form.year"
        value-format="YYYY"
        type="year"
        placeholder="请选择"
      />
    </el-form-item>
    <el-form-item label="季度">
      <el-select v-model="form.quarter" clearable size="large">
        <el-option label="第一季度" value="1"></el-option>
        <el-option label="第二季度" value="2"></el-option>
        <el-option label="第三季度" value="3"></el-option>
        <el-option label="第四季度" value="4"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="月度">
      <el-select v-model="form.monthly" clearable size="large">
        <el-option
          v-for="i in 12"
          :key="i"
          :label="i + `月`"
          :value="i"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="项目集">
      <el-cascader
        size="large"
        v-model="form.projectSetIdVal"
        :options="options"
        :props="props"
        clearable
        @change="cascaderChange"
        :show-all-levels="false"
      ></el-cascader>
    </el-form-item>
    <el-form-item>
      <el-button color="#fc702b" style="color: #fff" @click.prevent="onQuery"
        >查询</el-button
      >
      <el-button color="#f0f0f0" style="color: #000000" @click.prevent="onReset"
        >重置</el-button
      >
      <el-button class="button_edit" @click="onExport">
        <svg-icon
          icon-class="project-detail-icon-derive"
          class="icon-export m-r5"
        ></svg-icon>
        一键导出
      </el-button>
    </el-form-item>
  </el-form>
  <div>
    <public-table
      ref="publicTableRef"
      class="m-t20"
      index
      border
      :page="page"
      :tableData="tableData"
      :cell-style="{ background: 'revert' }"
      :tableOption.sync="tableOption"
      :objectSpanMethod="objectSpanMethod"
      @page-change="onPageChange"
      @handleSelectionChange="handleSelectionChange"
    >
      <template #departmentName="scope">
        <span style="color: blue; cursor: pointer" @click="toPage(scope.row)">{{
          scope.row.departmentName
        }}</span>
      </template>
    </public-table>
  </div>
</template>

<script setup>
import {
  ElDatePicker,
  ElDivider,
  ElOption,
  ElSelect,
  ElCascader,
  ElForm,
  ElFormItem,
} from "element-plus";
import { onMounted, reactive, ref } from "vue";
import { projectApi } from "@/api/project";
import { exportApi, fundManagementApi } from "@/api/businessFinance";
import PublicTable from "@/components/PublicTable.vue";
import { exportExcelFile } from "@/common/utils/GlobalUtils";
import { useRouter } from "vue-router";

const form = reactive({
  departmentId: "",
  projectName: "",
  year: "",
  monthly: "",
  type: "",
  projectSetIdVal: "",
});

const options = ref([]);
const props = reactive({
  value: "projectSetId",
  label: "projectSetName",
  children: "child",
});

/**
 * 获取当前年份
 */
const getYear = () => {
  return new Date().getFullYear().toString();
};

/**
 * 项目集级联选择器
 */
const cascaderChange = (e) => {
  if (e && e.length) {
    form.projectSetId = e[e.length - 1];
  }
  if (!e) {
    form.projectSetId = "";
  }
};

/**
 * 查询项目集树形结构
 */
const getProjectSetListTree = () => {
  projectApi.getProjectSetListTree({}).then((res) => {
    options.value = res.data;
  });
};

/**
 * 导出
 */
const onExport = () => {
  exportApi.fundBudgetPlanSetLeadingOut(form).then((res) => {
    if (res) {
      exportExcelFile(res, "资金预算台账");
    }
  });
};

/**
 * 筛选排序
 */
const filter = (arr, filed) => {
  let temObj = {};
  for (let i = 0; i < arr.length; i++) {
    let item = arr[i];
    if (!temObj[item[filed]]) {
      temObj[item[filed]] = [item];
    } else {
      temObj[item[filed]].push(item);
    }
  }
  let resArr = [];
  Object.keys(temObj).forEach((key) => {
    resArr.push({
      key: key,
      data: temObj[key],
    });
  });
  return resArr;
};

/**
 * 资金预算台账
 */
const getFundBudgetPlanList = (params) => {
  fundManagementApi.getFundBudgetPlanList(params).then((res) => {
    if (res.code === "200") {
      let data = [];
      res.data.content.forEach((item, index) => {
        item.list.forEach((val) => {
          data.push({
            ...item,
            ...val,
            index,
          });
        });
      });
      let arr = filter(data, "firstMainProjectName");
      let tempArr = [];
      for (let key in arr) {
        let obj = arr[key];
        tempArr.push(...obj.data);
      }
      tableData.value = tempArr;
      page.total = res.data.totalSize;
    }
  });
};

/**
 *
 */
const onQuery = () => {
  page.current = 1;
  page.size = 10;
  getFundBudgetPlanList({
    pageNum: page.current,
    pageSize: page.size,
    param: form,
  });
};

/**
 *
 */
const onReset = () => {
  form.departmentId = "";
  form.projectSetId = "";
  form.year = getYear();
  form.monthly = "";
  form.projectSetBelongId = "";
  form.type = "";
  form.quarter = "";
  form.projectSetIdVal = "";
  page.current = 1;
  page.size = 10;
  getFundBudgetPlanList({ pageNum: 1, pageSize: 10, param: form });
};

const page = reactive({
  total: 100,
  current: 1,
  size: 10,
});

const tableData = ref([]);

const tableOption = ref([
  {
    label: "填报部门",
    prop: "departmentName",
    minWidth: 80,
    slot: true,
    align: "center",
  },
  {
    label: "账套(归属名称)",
    prop: "projectSetBelongName",
    minWidth: 80,
    align: "center",
  },
  {
    label: "项目集 ",
    prop: "firstMainProjectName",
    minWidth: 80,
    align: "center",
  },
  {
    label: "项目子集 ",
    prop: "mainProjectName",
    minWidth: 80,
    align: "center",
  },
  { label: "年度", prop: "year", minWidth: 80, align: "center" },
  { label: "季度", prop: "quarter", minWidth: 80, align: "center" },
  { label: "月度", prop: "monthly", minWidth: 80, align: "center" },
  { label: "流入", prop: "inFlowAmount", minWidth: 80, align: "center" },
  { label: "流出", prop: "outFlowAmount", minWidth: 80, align: "center" },
  {
    label: "资金计划金额",
    prop: "budgetAmount",
    minWidth: 80,
    align: "center",
  },
  { label: "项目集合集", prop: "quarterAmount", minWidth: 80, align: "center" },
]);

// 合并表格
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  let data = tableData.value; //拿到当前table中数据
  let cellValue = row[column.property]; //当前位置的值
  if (columnIndex == 1 || columnIndex == 2 || columnIndex == 3) {
    let prevRow = data[rowIndex - 1]; //获取到上一条数据
    let nextRow = data[rowIndex + 1]; //下一条数据

    if (prevRow && prevRow[column.property] === cellValue) {
      //当有上一条数据，并且和当前值相等时
      return { rowspan: 0, colspan: 0 };
    } else {
      let countRowspan = 1;
      while (nextRow && nextRow[column.property] === cellValue) {
        //当有下一条数据并且和当前值相等时,获取新的下一条
        nextRow = data[++countRowspan + rowIndex];
      }
      if (countRowspan > 1) {
        return { rowspan: countRowspan, colspan: 1 };
      }
    }
  } else if (columnIndex == 5 || columnIndex == 6) {
    let prevRow = data[rowIndex - 1]; //获取到上一条数据
    let nextRow = data[rowIndex + 1]; //下一条数据
    if (
      prevRow &&
      prevRow[column.property] === cellValue &&
      prevRow.carNum == row.carNum
    ) {
      //当有上一条数据，并且和当前值相等时
      return { rowspan: 0, colspan: 0 };
    } else {
      let countRowspan = 1;
      while (
        nextRow &&
        nextRow[column.property] === cellValue &&
        nextRow.carNum == row.carNum
      ) {
        //当有下一条数据并且和当前值相等时,获取新的下一条
        nextRow = data[++countRowspan + rowIndex];
      }
      if (countRowspan > 1) {
        return { rowspan: countRowspan, colspan: 1 };
      }
    }
  } else if (columnIndex == 11) {
    let prevRow = data[rowIndex - 1]; //获取到上一条数据
    let nextRow = data[rowIndex + 1]; //下一条数据
    if (
      prevRow &&
      prevRow.carNum == row.carNum &&
      prevRow.index === row.index
    ) {
      //当有上一条数据，并且和当前值相等时
      return { rowspan: 0, colspan: 0 };
    } else {
      let countRowspan = 1;
      while (
        nextRow &&
        nextRow.carNum == row.carNum &&
        nextRow.index === row.index
      ) {
        //当有下一条数据并且和当前值相等时,获取新的下一条
        nextRow = data[++countRowspan + rowIndex];
      }
      if (countRowspan > 1) {
        return { rowspan: countRowspan, colspan: 1 };
      }
    }
  }
};

const onPageChange = (e) => {
  page.current = e.page;
  page.size = e.limit;
  let param = {
    param: {
      ...form,
    },
    pageNum: page.current,
    pageSize: page.size,
  };
  getFundBudgetPlanList(param);
};

const projectSetBelong = ref([]);
/**
 * 获取项目集归属
 */
const getProjectSetBelong = () => {
  projectApi.getProjectSetBelong().then((res) => {
    if (res.code === "200") {
      projectSetBelong.value = res.data;
    }
  });
};

const handleSelectionChange = (e) => {
  console.log(e);
};

/**
 * 跳转到详情页
 */
const router = useRouter();
const toPage = ({ departmentId, projectSetBelongId }) => {
  router.push({
    path: `/businessFinance/fundManagement/fundBudgetManagement/budgetLedger7/id=${form.year}&projectSetBelongId=${projectSetBelongId}&departmentId=${departmentId}`,
  });
};

onMounted(() => {
  getProjectSetListTree();
  form.year = getYear();
  getFundBudgetPlanList({ pageNum: 1, pageSize: 10, param: form });
  getProjectSetBelong();
});
</script>

<style lang="scss" scoped></style>
